<template>
  <div class="report-management">
    <div class="header-with-back">
      <button class="back-btn" @click="$emit('back')">
        <el-icon><ArrowLeft /></el-icon> 返回
      </button>
      <h1 class="page-title">举报管理</h1>
    </div>
    
    <LoadingSpinner v-if="isLoading" message="加载举报数据..." />
    
    <div v-else class="report-management-content">
      <!-- 筛选区域 -->
      <div class="filters-row">
        <div class="filter-group">
          <label>状态筛选:</label>
          <select v-model="statusFilter">
            <option value="all">全部状态</option>
            <option value="pending">待处理</option>
            <option value="processed">已处理</option>
            <option value="rejected">已驳回</option>
          </select>
        </div>
        
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索举报内容..." 
            @input="handleSearch"
          >
        </div>
      </div>
      
      <div v-if="filteredReports.length === 0" class="no-reports">
        暂无举报数据
      </div>
      
      <div v-else class="reports-table-container">
        <table class="reports-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>举报原因</th>
              <th>举报人</th>
              <th>被举报人</th>
              <th>关联书籍</th>
              <th>状态</th>
              <th>提交时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="report in filteredReports" :key="report.id">
              <td>{{ report.id }}</td>
              <td class="report-reason">{{ getReasonText(report.reason) }}</td>
              <td>{{ report.reporter_id }}</td>
              <td>{{ report.reported_id }}</td>
              <td>{{ report.book_id }}</td>
              <td>
                <span :class="`tag tag-${report.status}`">{{ getStatusText(report.status) }}</span>
              </td>
              <td>{{ formatDate(report.created_at) }}</td>
              <td>
                <button class="btn btn-primary" @click="showReportDetail(report)">详情</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 举报详情对话框 -->
    <div class="modal" v-if="showDetailModal">
      <div class="modal-content">
        <h3>举报详情</h3>
        
        <div class="report-detail" v-if="selectedReport">
          <div class="detail-row">
            <div class="detail-label">举报ID:</div>
            <div class="detail-value">{{ selectedReport.id }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">举报原因:</div>
            <div class="detail-value">{{ selectedReport.reason }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">详细说明:</div>
            <div class="detail-value detail-text">{{ selectedReport.details }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">举报人ID:</div>
            <div class="detail-value">{{ selectedReport.reporter_id }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">被举报人ID:</div>
            <div class="detail-value">{{ selectedReport.reported_id }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">关联书籍ID:</div>
            <div class="detail-value">{{ selectedReport.book_id }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">提交时间:</div>
            <div class="detail-value">{{ formatDate(selectedReport.created_at) }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">状态:</div>
            <div class="detail-value">
              <span :class="`tag tag-${selectedReport.status}`">{{ getStatusText(selectedReport.status) }}</span>
            </div>
          </div>
          
          <div class="detail-row" v-if="selectedReport.status !== 'pending'">
            <div class="detail-label">管理员备注:</div>
            <div class="detail-value">{{ selectedReport.admin_comment || '无' }}</div>
          </div>
          
          <!-- 处理举报区域 -->
          <div class="process-report" v-if="selectedReport.status === 'pending'">
            <h4>处理举报</h4>
            <div class="form-group">
              <label>管理员备注</label>
              <textarea v-model="adminComment" rows="3" placeholder="请输入处理意见..."></textarea>
            </div>
            <div class="action-buttons">
              <button class="btn btn-success" @click="handleReport('processed')">接受举报</button>
              <button class="btn btn-danger" @click="handleReport('rejected')">驳回举报</button>
            </div>
          </div>
        </div>
        
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- Toast通知组件 -->
    <Toast 
      :message="toastMessage" 
      :type="toastType" 
      :visible="showToast" 
      @close="showToast = false" 
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '@/api/apiClient'
import Toast from '@/components/Toast.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

// 定义事件
defineEmits(['back'])

// 状态变量
const reports = ref([])
const isLoading = ref(true)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('info')
const statusFilter = ref('all')
const searchQuery = ref('')
const showDetailModal = ref(false)
const selectedReport = ref(null)
const adminComment = ref('')

// 获取状态文本
const getStatusText = (status) => {
  switch(status) {
    case 'pending': return '待处理';
    case 'processed': return '已处理';
    case 'rejected': return '已驳回';
    default: return status;
  }
}

//举报原因文本状态转换
const getReasonText = (reason) => {
    switch(reason) {
        case 'fake': return '虚假信息';
        case 'inappropriate': return '不当内容';
        case 'scam': return '诈骗行为';
        case 'other': return '其他原因';
        default: return reason;
    }
}

// 显示通知
const showNotification = (message, type = 'info') => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true
}

// 获取举报数据
const fetchReports = async () => {
  isLoading.value = true
  try {
    const response = await api.admin.getReportList()
    
    if (response && response.reports) {
      reports.value = response.reports
      console.log('获取举报数据成功:', reports.value)
    } else {
      console.error('获取举报数据失败: 返回格式不正确', response)
      reports.value = [] 
    }
  } catch (error) {
    console.error('获取举报数据失败:', error)
    reports.value = []
    showNotification('获取举报数据失败', 'error')
  } finally {
    isLoading.value = false
  }
}

// 状态筛选
const getStatusFilter = (report, status) => {
  if (status === 'all') return true;
  return report.status === status;
}

// 搜索函数
const handleSearch = () => {
  console.log('搜索内容:', searchQuery.value)
}

// 筛选后的举报列表
const filteredReports = computed(() => {
  if (reports.value.length === 0) return [];
  
  // 筛选
  return reports.value.filter(report => {
    const statusMatches = getStatusFilter(report, statusFilter.value);
    const searchMatches = searchQuery.value === '' || 
      report.reason?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      report.details?.toLowerCase().includes(searchQuery.value.toLowerCase());
    
    return statusMatches && searchMatches;
  });
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 显示举报详情
const showReportDetail = (report) => {
  selectedReport.value = report;
  adminComment.value = report.admin_comment || '';
  showDetailModal.value = true;
}

// 关闭详情对话框
const closeDetailModal = () => {
  showDetailModal.value = false;
  selectedReport.value = null;
  adminComment.value = '';
}

// 处理举报
const handleReport = async (status) => {
  if (!selectedReport.value) return;
  
  // 验证管理员备注
  if (!adminComment.value.trim()) {
    showNotification('请填写处理意见', 'warning');
    return;
  }
  
  try {
    // 按照API要求组织参数
    await api.admin.handleReport(selectedReport.value.id, {
      status: status,  // processed 或 rejected
      admin_comment: adminComment.value  // 管理员备注
    });
    
    // 更新本地数据
    const reportIndex = reports.value.findIndex(r => r.id === selectedReport.value.id);
    if (reportIndex !== -1) {
      reports.value[reportIndex].status = status;
      reports.value[reportIndex].admin_comment = adminComment.value;
    }
    
    showNotification(`举报已${status === 'processed' ? '接受' : '驳回'}`, 'success');
    closeDetailModal();
  } catch (error) {
    console.error('处理举报失败:', error);
    showNotification('处理举报失败: ' + (error.message || '未知错误'), 'error');
  }
}

// 组件加载时获取数据
onMounted(async () => {
  await fetchReports()
})
</script>

<style scoped>
.report-management {
  width: 100%;
  position: relative;
}

.header-with-back {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
}

.back-btn {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: #3b82f6;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  padding: 0.5rem 0.75rem;
  margin-right: 1rem;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #eff6ff;
}

.page-title {
  margin-bottom: 0;
  font-size: 1.8rem;
  color: #374151;
}

.report-management-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1.5rem;
}

.filters-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 160px;
}

.filter-group label {
  font-size: 0.875rem;
  color: #4b5563;
  margin-bottom: 0.25rem;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.search-box {
  flex-grow: 1;
  display: flex;
  align-items: flex-end;
}

.search-box input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.no-reports {
  text-align: center;
  padding: 3rem 0;
  color: #6b7280;
  font-size: 1.1rem;
}

.reports-table-container {
  overflow-x: auto;
}

.reports-table {
  width: 100%;
  border-collapse: collapse;
}

.reports-table th,
.reports-table td {
  padding: 0.75rem 1rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.reports-table th {
  background-color: #f9fafb;
  font-weight: 500;
  color: #374151;
}

.report-reason {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.tag-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.tag-processed {
  background-color: #dcfce7;
  color: #166534;
}

.tag-rejected {
  background-color: #fee2e2;
  color: #991b1b;
}

.btn {
  padding: 0.375rem 0.75rem;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  border: none;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-success {
  background-color: #10b981;
  color: white;
}

.btn-success:hover {
  background-color: #059669;
}

.btn-danger {
  background-color: #ef4444;
  color: white;
}

.btn-danger:hover {
  background-color: #dc2626;
}

.btn-secondary {
  background-color: #9ca3af;
  color: white;
}

.btn-secondary:hover {
  background-color: #6b7280;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  width: 100%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.modal-content h3 {
  margin-top: 0;
  color: #1f2937;
  margin-bottom: 1.5rem;
}

.report-detail {
  margin-bottom: 1.5rem;
}

.detail-row {
  display: flex;
  margin-bottom: 0.75rem;
  border-bottom: 1px solid #f3f4f6;
  padding-bottom: 0.75rem;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-label {
  width: 120px;
  font-weight: 500;
  color: #4b5563;
}

.detail-value {
  flex: 1;
}

.detail-text {
  white-space: pre-line;
  color: #1f2937;
  background-color: #f9fafb;
  padding: 0.75rem;
  border-radius: 4px;
  margin-top: 0.5rem;
}

.process-report {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.process-report h4 {
  margin-top: 0;
  color: #1f2937;
  margin-bottom: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #4b5563;
}

.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  resize: vertical;
}

.action-buttons {
  display: flex;
  gap: 0.75rem;
  margin-top: 1rem;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

@media (max-width: 768px) {
  .filters-row {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .filter-group,
  .search-box {
    width: 100%;
  }
  
  .detail-row {
    flex-direction: column;
  }
  
  .detail-label {
    width: 100%;
    margin-bottom: 0.25rem;
  }
}
</style> 